<!--
 * @Author: zhangjingyu
 * @Date: 2020-10-22 19:29:59
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-04-28 16:04:02
 * @FilePath: \vprisk10.14\src\views\PublicManage\publicManage\dimensionManage\dimensionHierarchy.vue
 * @Description: 维度层级
-->

<template>
  <!-- 维度层级页面 -->
  <div>
    <el-row :gutter="20">
      <el-col :span="18" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          @search="searchForm.pageNo=1,searchFunc()"
          @clear="
            (searchForm.treetypeCode = ''),
              (searchForm.treetypeName = ''),
              (searchForm.relatedDicttypeCode = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addFunc">新增</el-button>
            <el-button @click="editFunc">编辑</el-button>
            <el-button @click="deleteFunc">删除</el-button>
            <el-button @click="viewFunc">查看</el-button>
            <el-button @click="configFun">配置层级</el-button>
            <el-button @click="setAsDefault">设为默认</el-button>
          </template>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="100px"
              label-position="right"
              size="mini"
            >
              <el-form-item label="编码：">
                <el-input
                  v-model="searchForm.treetypeCode"
                  placeholder="请输入编码"
                ></el-input>
              </el-form-item>
              <el-form-item label="名称：" prop="treetypeName">
                <el-input
                  v-model="searchForm.treetypeName"
                  placeholder="请输入名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="所属维度：" prop="relatedDicttypeCode">
                <el-select
                  v-model="searchForm.relatedDicttypeCode"
                  placeholder="请选择"
                  style="width:100%"
                  clearable
                >
                  <el-option
                    v-for="item in relatedDicttypeCodeList"
                    :key="item.dictCode"
                    :label="item.dictName"
                    :value="item.dictCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </template>
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in textData"
                :label="item.label"
                :disabled="item.checkDisabled"
                :key="item.prop"
                >{{ item.label }}</el-checkbox
              >
            </el-checkbox-group>
          </template>
        </upper-template>

        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="getTree"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            v-for="(item, key) in showData"
            :key="key"
            :prop="item.prop"
            :label="item.label"
            :show-overflow-tooltip="true"
            :render-header="item.render"
            :sortable="item.sortable"
            :formatter="item.formatter"
            :width="item.width"
            :min-width="item.minwidth"
          ></el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.pageNo"
          :total="total"
           :page-size="searchForm.pageSize"
          @refresh="searchFunc"
        ></pagination>
      </el-col>
      <el-col :span="6" class="content-right">
        <div class="title">
          <div style="float:left"><span class="gun"></span> {{ treeName }}</div>
        </div>
        <vp-tree
          vp-title="层级"
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          ref="caliberTree"
          node-key="dictItemCode"
          :render-content="renderTree"
          :footerBtn="true"
        >
        </vp-tree>
      </el-col>
    </el-row>
    <!-- 新增编辑查看弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
      top="1%"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="97px"
        label-position="left"
        :rules="saveFormRule"
        :disabled="saveFlg == 3"
      >
        <el-form-item label="编码：" prop="treetypeCode">
          <el-input
            v-model.trim="saveForm.treetypeCode"
            :disabled="saveFlg != 1"
          ></el-input>
        </el-form-item>
        <el-form-item label="名称：" prop="treetypeName">
          <el-input v-model.trim="saveForm.treetypeName"></el-input>
        </el-form-item>
        <el-form-item label="所属维度：" prop="dictCode">
          <el-select
            v-model="saveForm.dictCode"
            placeholder="请选择"
            style="width:100%"
          >
            <el-option
              v-for="item in relatedDicttypeCodeList"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述：" prop="descn">
          <el-input v-model="saveForm.descn" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc" v-if="saveFlg != 3">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 配置层级弹窗 -->
    <el-dialog
      v-dialogDrag
      title="维度层级配置"
      :visible.sync="isConfigDialog"
      width="70%"
    >
      <el-row :gutter="10">
        <el-col :span="14">
          <upper-template
            @search="searchFF.pageNo=1,searchFFunc()"
            @clear="(searchFF.dictItemName = ''), (searchFF.dictItemCode = '')"
          >
            <div slot="searchArea">
              <el-form
                :model="searchFF"
                ref="searchFF"
                label-width="87px"
                label-position="left"
                size="mini"
              >
                <el-form-item label="维度编码：">
                  <el-input v-model="searchFF.dictItemCode"></el-input>
                </el-form-item>
                <el-form-item label="维度名称：" prop="caliberProjectName">
                  <el-input v-model="searchFF.dictItemName"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <!-- 显示隐藏区 -->
            <template slot="columnHide">
              <el-checkbox-group :value="[1, 2]" disabled>
                <el-checkbox :label="1">维度编码</el-checkbox>
                <el-checkbox :label="2">维度名称</el-checkbox>
              </el-checkbox-group>
            </template>
          </upper-template>

          <el-table
            ref="configTable"
            :data="configTableData"
            style="width: 100%"
            @row-click="configTableRowClick"
          >
            <el-table-column
              width="55"
              type="selection"
            ></el-table-column>
            <el-table-column
              v-for="(item, key) in showConfigData"
              :key="key"
              :prop="item.prop"
              :label="item.label"
              :align="item.align"
              :width="item.width"
              :show-overflow-tooltip="true"
              :render-header="item.render"
              :sortable="item.sortable"
              :formatter="item.formatter"
            ></el-table-column>
          </el-table>

          <pagination
            @size-change="handleSizeChangeConf"
            @current-change="handleCurrentChangeConf"
            :current-page="searchFF.pageNo"
            @refresh="searchFFunc"
            :pager-count="5"
            :page-size="searchFF.pageSize"
            :total="totalConf"
          ></pagination>
        </el-col>
        <el-col :span="10">
          <upper-template noIcon>
            <div slot="buttonArea">
              <el-button @click="addNextNode">新增下级节点</el-button>
              <el-button @click="delNode">删除</el-button>
            </div>
          </upper-template>
          <vp-tree
            vp-title="层级"
            :data="treeDataConf"
            :props="defaultProps"
            @node-click="handleNodeClick"
            @check="handleNodeClick"
            default-expand-all
            show-checkbox
            ref="caliberConfigTree"
            node-key="dictItemCode"
            check-strictly
            check-on-click-node
            :expand-on-click-node="false"
            :render-content="renderTree"
          ></vp-tree>
        </el-col>
      </el-row>

      <div slot="footer"></div>
    </el-dialog>
  </div>
</template>

<script>
// import iscroll from 'iscroll'
import { publicManage_pub } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue";
import moment from "moment";
export default {
  components: {
    upperTemplate
  },
  data() {
    return {
      treeName: "",
      addOrEdit: false, // 新增/编辑/查看弹窗
      isConfigDialog: false, // 配置层级弹窗
      serachMore: false, // 配置层级搜索是否收起
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      relatedDicttypeCodeList: [],
      saveTitles: ["新增维度层级", "修改维度层级", "查看维度层级"],
      searchForm: {
        pageSize: 15,
        pageNo: 1,
        treetypeCode: '',
        treetypeName: '',
        relatedDicttypeCode: ''
      },
      total: 0,
      saveForm: {
        treetypeCode: "",
        treetypeName: "",
        dictCode: "",
        descn: ""
      },
      saveFormRule: {
        treetypeCode: [
          { required: true, message: "请输入层级树编码", trigger: "blur" },
          {
            pattern: /^TR[0-9a-zA-Z_]{0,50}$/,
            message: "编码必须以TR开头，可输入数字、字母、下划线",
            trigger: "blur"
          },
          { validator: this.treetypeCodeValid, trigger: "blur" }
        ],
        treetypeName: [
          { required: true, message: "请输入层级树名称", trigger: "blur" },
          { validator: this.treetypeNameValid, trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        dictCode: [
          { required: true, message: "请选择口径方案", trigger: "blur" }
        ]
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        {
          prop: "treetypeCode",
          label: "编码",
          align: "center",
          checkDisabled: true
        },
        {
          prop: "treetypeName",
          label: "名称",
          sortable: true,
          checkDisabled: true
        },
        {
          prop: "relatedDicttypeCode.dictName",
          label: "所属维度 ",
          checkDisabled: true
        },
        {
          prop: "defaultTree",
          label: "是否默认",
          formatter: row => {
            return row.defaultTree == 1 ? "是" : "否";
          }
        },
        { prop: "descn", label: "描述" },
        {
          prop: "creator",
          label: "创建人",
          formatter: row => {
            return row.creator || "-";
          }
        },
        {
          prop: "createdTm",
          label: "创建时间",
          align: "right",
          formatter: row => {
            return this.timeFormat(row.createdTm);
          }
        },
        {
          prop: "modifier",
          label: "修改人",
          formatter: row => {
            return row.modifier || "-";
          }
        },
        {
          prop: "modifiedTm",
          label: "修改时间",
          align: "right",
          formatter: row => {
            return this.timeFormat(row.modifiedTm);
          }
        }
      ],
      // 获取table的数据
      tableData: [],
      defaultProps: {
        children: "children",
        label: "dictItemName"
      },
      checkedRow: {}, // 选中主表row,供层及配置使用
      treeData: [],
      treeDataConf: [],
      searchFF: {
        dictItemCode: "",
        dictItemName: "",
        pageNo: 1,
        pageSize: 15
      },
      totalConf: 0,
      // 口径层级配置表格列配置
      showConfigData: [
        { prop: "dictItemCode", label: "维度编码", align: "right" },
        { prop: "dictItemName", label: "维度名称" }
      ],
      configTableData: []
    };
  },
  computed: {
    // 展示字段
    showData() {
      let arr = this.textData.map(v => {
        return v.label;
      });
      let valArr = [],
        showData = [];
      // 选中的字段排序
      arr.forEach(element => {
        let flag = false;
        this.checkList.forEach(e => {
          if (e == element) {
            flag = true;
          }
        });
        if (flag) {
          valArr.push(element);
        }
      });
      // 控制表列隐藏显示
      for (let i = 0; i < this.checkList.length; i++) {
        for (let j = 0; j < this.textData.length; j++) {
          if (this.textData[j].label == valArr[i]) {
            let item = { ...this.textData[j] };
            showData.push(item);
          }
        }
      }
      return showData;
    }
  },
  watch: {
    addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    }
  },
  created() {
    this.getDict();
    this.checkListInit();
    this.$nextTick(() => {
      this.searchFunc();
    });
  },
  methods: {
    getDict() {
      publicManage_pub.dimDicttypeListQuery().then(res => {
        if (res.code == 200) {
          this.relatedDicttypeCodeList = res.data;
        }
      });
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    searchFunc() {
      let data = this.searchForm;
      publicManage_pub.dimensionIndexQuery(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.total = res.count;
        }
      });
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
      this.$nextTick(() => {
        // 清除校验结果
        this.$refs.saveForm.clearValidate();
      });
    },

    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = {
        treetypeId: row.treetypeId,
        treetypeCode: row.treetypeCode,
        treetypeName: row.treetypeName,
        dictCode: row.relatedDicttypeCode.dictCode,
        descn: row.descn
      };
      this.saveForm = form;
      this.addOrEdit = true;
    },
    // 保存
    saveFunc() {
      console.log(this.saveForm);
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = {
            ...this.saveForm
          };
          publicManage_pub.dimensionIndexSave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.addOrEdit = false;
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        }
      });
    },
    deleteFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: selection.map(v => v.treetypeId).toString() };
          publicManage_pub.dimensionIndexDelete(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message + "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    viewFunc() {
      this.saveFlg = 3;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据查看");
      }
      let row = selection[0];
      let form = {
        treetypeId: row.treetypeId,
        treetypeCode: row.treetypeCode,
        treetypeName: row.treetypeName,
        dictCode: row.dictCode,
        descn: row.descn
      };
      this.saveForm = form;
      this.addOrEdit = true;
    },
    setAsDefault() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let row = selection[0];
      let data = {
        treetypeId: row.treetypeId,
        relatedDicttypeCode: row.relatedDicttypeCode.dictCode
      };
      publicManage_pub.dimensionIndexSetDefault(data).then(res => {
        if (res.code == 200) {
          this.$message.success("设为默认成功");
          this.searchFunc();
        } else {
          this.$message.error(res.message || "设为默认失败");
        }
      });
    },
    handleNodeClick(obj) {
      let node = { ...obj };
      this.$refs.caliberConfigTree.$tree.setCheckedNodes([]);
      this.$refs.caliberConfigTree.$tree.setCheckedNodes([node]);
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    // 获取口径树
    getTree(row) {
      this.treeName = row.treetypeName;
      this.checkedRow = row;
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row, true);
      console.log(row);
      let data = { dimTreetypeCode: row.treetypeCode };
      publicManage_pub.dimensionIndexGetTree(data).then(res => {
        if (res.code == 200) {
          let arr = res.data
            this.treeData = this.$listToTree(
            "dictItemCode",
            "parentItemCode",
            arr
          );
        }
        // if(!res){
        //   this.getTree(row)
        // }
      });
    },
    // 编号是否重复校验
    treetypeCodeValid(rule, value, callback) {
      // 只在新增时校验
      if (this.saveFlg != 1) {
        callback();
        return;
      }
      publicManage_pub
        .dimensionIndexCheckTreetypeCode({ treetypeCode: value })
        .then(res => {
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error(res.message + "，编号已存在"));
          }
        });
    },
    // 名称是否重复校验
    treetypeNameValid(rule, value, callback) {
      // 只在新增时校验
      let data = {
        treetypeCode: this.saveForm.treetypeCode,
        treetypeName: value
      };
      if (this.saveFlg == 1) {
        data.treetypeCode = "";
      }
      publicManage_pub.dimensionIndexCheckTreetypeName(data).then(res => {
        if (res.code == 200) {
          callback();
        } else {
          callback(new Error("名称已存在"));
        }
      });
    },
    // 层级配置表行点击事件处理
    configTableRowClick(row) {
      this.$refs.configTable.clearSelection();
      this.$refs.configTable.toggleRowSelection(row);
    },
    configFun() {
      let checked = this.$refs.multipleTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.isConfigDialog = true;
        this.configRow = checked[0];
        this.configRow.dictCode = checked[0].relatedDicttypeCode.dictCode;
        this.getConfTree();
        this.$nextTick(() => {
          this.searchFFunc();
        });
      }
    },
    getConfTree() {
      publicManage_pub
        .dimensionIndexGetTree({ dimTreetypeCode: this.configRow.treetypeCode })
        .then(res => {
          if (res.code == 200) {
            this.treeDataConf = this.$listToTree(
              "dictItemCode",
              "parentItemCode",
              res.data
            );
          }
        });
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.searchFunc();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.searchForm.pageNo = val;
      this.searchFunc();
      console.log(`当前页: ${val}`);
    },
     handleSizeChangeConf(val) {
      this.searchFF.pageSize = val;
      this.searchFFunc();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChangeConf(val) {
      this.searchFF.pageNo = val;
      this.searchFFunc();
      console.log(`当前页: ${val}`);
    },
    // 口径层级配置弹窗左表查询
    searchFFunc() {
      let data = {
        treeTypeCode: this.configRow.treetypeCode,
        dictCode: this.configRow.dictCode,
        ...this.searchFF
      };
      publicManage_pub.dimensionIndexQueryGridForTree(data).then(res => {
        this.configTableData = res.data;
        this.totalConf = res.count;
      });
    },
    // 增加下级节点
    addNextNode() {
      let node = this.$refs.caliberConfigTree.$tree.getCheckedNodes();
      let selection = this.$refs.configTable.selection;
      if (node.length !== 1) {
        return this.$message.warning("请选择一个树节点");
      }
      if (selection.length < 1) {
        return this.$message.warning("请选择要添加到层级树的维度成员");
      }
      console.log(node, "node");
      let data = {
        dictCodeOfTreetype: this.configRow.relatedDicttypeCode.dictCode,
        dictItemIds: selection.map(v => v.dictItemId).toString(),
        parentNodeItemCode: node[0].dictItemCode,
        treetypeCode: this.configRow.treetypeCode
      };
      publicManage_pub.dimensionIndexAddChildNode(data).then(res => {
        if (res.code == 200) {
          this.$message.success("添加成功");
          this.searchFFunc();
          this.getConfTree();
        } else {
          this.$message.error(res.message || "添加失败");
        }
      });
    },
    // 删除节点
    delNode() {
      let nodes = this.$refs.caliberConfigTree.$tree.getCheckedNodes();
      console.log(nodes);
      if (nodes.length < 1) {
        return this.$message.warning("请选择要删除的节点");
      }
      if (!nodes[0].parentItemCode) {
        return this.$message.warning("根节点不允许删除");
      }
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            treetypeCode: this.configRow.treetypeCode,
            dictItemCode: nodes[0].dictItemCode
          };
          publicManage_pub.dimensionIndexRemoveNode(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFFunc();
              this.getConfTree();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    renderTree(h, { node, data, store }) {
      return <span title={data.dictItemCode + "-" + data.dictItemName}>{data.dictItemCode + "-" + data.dictItemName}</span>;
    },
    timeFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "-";
    }
  }
};
</script>

<style lang="scss" scoped>
</style>